import random
import redis
from django import  forms
from app01  import models
from django.conf import settings
from django.http import JsonResponse
from utils.tencent.sms import send_sms_single
from django.shortcuts import render,HttpResponse
from django.core.validators import RegexValidator
from django.views.decorators.csrf import csrf_exempt



# Create your views here.

class RegisterModelForm(forms.ModelForm):
    password = forms.CharField(label="密码",widget=forms.PasswordInput(render_value=True))
    confirm_pwd = forms.CharField(label='确认密码',widget=forms.PasswordInput(render_value=True))#render_value=True设置是否保留输入框数据
    mobile_phone = forms.CharField(label="手机号",validators=[RegexValidator(r'^1[3-9]\d{9}$','手机号格式错误')])
    code = forms.CharField(label="验证码",widget=forms.TextInput())
    class Meta:
        model = models.UserInfo
        fields = ["username","email","password","confirm_pwd","mobile_phone","code"]

    def __init__(self,*args,**kwargs):
        super().__init__(*args,**kwargs)
        for name,field in self.fields.items():
            field.widget.attrs = {'class': 'form-control', "placeholder": field.label}


conn = redis.Redis(host='127.0.0.1',
                   port=6379,
                   password="631521",
                   encoding="utf-8")

def sms_test(request):
    tel = request.GET.get("tel")
    type = request.GET.get("type")
    template_id = settings.SMS_TEMPLATE_ID.get(type)
    if template_id:
            code = random.randrange(1000,9999)
            res = send_sms_single(tel,template_id,[code,])
            if res["result"] ==0:
                conn.set(tel,code,ex=60)#ex=设置时长
                return JsonResponse({"status":True,"msg":"发送成功"})
            return JsonResponse({"status":False,"msg":res["errmsg"]})
    return JsonResponse({"status":False,"msg":'找不到模板'})


@csrf_exempt
def register(request):
    if request.method =="GET":
        form = RegisterModelForm()
        return render(request, "app01/register.html", {"form": form, "title": "注册"})
    form = RegisterModelForm(data=request.POST)
    if form.is_valid():
       redis_code = conn.get(request.POST['mobile_phone'])
       input_code = request.POST['code']
       if redis_code:
           if redis_code.decode("utf8") == input_code:
                form.save()
                return HttpResponse("注册成功")
           form.add_error("code", "验证码错误")
           return render(request, "app01/register.html", {"form": form, "title": "注册"})
       form.add_error("code","验证码已失效")
       return render(request, "app01/register.html", {"form": form, "title": "注册"})
    return  render(request, "app01/register.html", {"form":form, "title": "注册"})
